package com.livepass.android.girlspicks.helps;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.livepass.android.girlspicks.adapters.ArticleTableAdapter;

public class ContentProviderDB extends ContentProvider {
	public static final String AUTHORITY = "com.livepass.database";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);

	private DBHelper mDbHelper;

	// content Provider Override

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean onCreate() {
		mDbHelper = new DBHelper(getContext());
		/**
		 * Create a write able database which will trigger its creation if it
		 * doesn't already exist.
		 */
		return (mDbHelper == null) ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		String table = getTableName(uri);
		SQLiteDatabase database = mDbHelper.getReadableDatabase();
		Cursor cursor = database.query(table, projection, selection,
				selectionArgs, null, null, sortOrder);
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		String table = getTableName(uri);
		SQLiteDatabase database = mDbHelper.getWritableDatabase();
		return database.update(table, values, selection, selectionArgs);
	}

	@Override
	public int delete(Uri uri, String where, String[] selectionArgs) {
		String table = getTableName(uri);
		SQLiteDatabase dataBase = mDbHelper.getWritableDatabase();
		return dataBase.delete(table, where, selectionArgs);
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase mDB = mDbHelper.getWritableDatabase();
		long rowID = mDB.insert(getTableName(uri), null, values);
		if (rowID > 0) {
			Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
		throw new SQLException("Failed to add a record into " + uri);
	}

	public String getTableName(Uri uri) {
		String value = uri.getLastPathSegment();
		// Log.e("----------TABLE--------------",value);
		return value;
	}

	public static void clearAllData(Context context) {
		ArticleTableAdapter.getInstance(context).clear();
	}

}